<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="菜单权限管理">
        页面数据为 Mock 示例数据，非真实数据。
      </n-card>
    </div>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-dropdown trigger="hover" @select="selectAddMenu" :options="addMenuOptions">
                <n-button type="info" ghost icon-placement="right">
                  添加菜单
                  <template #icon>
                    <div class="flex items-center">
                      <n-icon size="14">
                        <DownOutlined />
                      </n-icon>
                    </div>
                  </template>
                </n-button>
              </n-dropdown>
              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line
                  cascade
                  checkable
                  :virtual-scroll="true"
                  :pattern="pattern"
                  :data="treeData"
                  :expandedKeys="expandedKeys"
                  style="max-height: 650px; overflow: hidden"
                  :default-checked-keys="defaultCheckedMenu"
                  :check-strategy="'parent'"
                  @update:selected-keys="selectedTree"
                  @update:checked-keys="checkedTree"
                  @update:expanded-keys="onExpandedKeys"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>编辑菜单{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
            </n-space>
          </template>
          <n-alert type="info" closable> 从菜单列表选择一项后，进行编辑</n-alert>
          <n-form
            :model="formParams"
            :rules="rules"
            ref="formRef"
            label-placement="left"
            :label-width="100"
            v-if="isEditMenu"
            class="py-4"
          >

            {{formParams}}
            <n-form-item label="类型" path="type">
              <span>{{ formParams.type === 1 ? '侧边栏菜单' : '' }}</span>
            </n-form-item>
            <n-form-item label="标题" path="name">
              <n-input placeholder="请输入标题" v-model:value="formParams.name" />
            </n-form-item>
<!--            <n-form-item label="副标题" path="subtitle">-->
<!--              <n-input placeholder="请输入副标题" v-model:value="formParams.subtitle" />-->
<!--            </n-form-item>-->
            <n-form-item label="路径" path="path">
              <n-input placeholder="请输入路径" v-model:value="formParams.path" />
            </n-form-item>
<!--            <n-form-item label="打开方式" path="openType">-->
<!--              <n-radio-group v-model:value="formParams.openType" name="openType">-->
<!--                <n-space>-->
<!--                  <n-radio :value="1">当前窗口</n-radio>-->
<!--                  <n-radio :value="2">新窗口</n-radio>-->
<!--                </n-space>-->
<!--              </n-radio-group>-->
<!--            </n-form-item>-->
            <n-form-item label="是否隐藏" path="openType">
              <n-radio-group v-model:value="formParams.hidden" name="hidden">
                <n-space>
                  <n-radio :value="1">是</n-radio>
                  <n-radio :value="0">否</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="菜单权限" path="permissions">
              <n-input placeholder="请输入权限，多个权限用，分割" v-model:value="formParams.permissions" />
            </n-form-item>
            <n-form-item path="auth" style="margin-left: 100px">
              <n-space>
                <n-button type="primary" :loading="subLoading" @click="formSubmit"
                  >保存修改</n-button
                >
                <n-button @click="handleReset">重置</n-button>
                <n-button @click="handleDel">删除</n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-card>
      </n-gi>
    </n-grid>

    <!-- 原框架没有上级id? 没有上级id怎么添加子级? -->
    <CreateDrawer ref="createDrawerRef" :title="drawerTitle" :parentMenuId="treeItemId" @refresh-menu="getTreeMenuList"/>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted, computed } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { DownOutlined, AlignLeftOutlined, SearchOutlined, FormOutlined } from '@vicons/antd';
  import { deleteById, getMenuList, saveMenu } from "@/api/system/menu";
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import { storage } from '@/utils/Storage';
  import { CURRENT_USER } from '@/store/mutation-types';
  import { updatePermissions } from '@/api/system/user';
  import { ResultEnum } from "@/enums/httpEnum";

  const rules = {
    label: {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
    path: {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
  };

  const formRef: any = ref(null);
  const createDrawerRef = ref();
  const message = useMessage();
  const dialog = useDialog();
  const defaultCheckedMenu = ref(['菜单权限管理']);

  let currentUserInfo = storage.get(CURRENT_USER);
  if (currentUserInfo && currentUserInfo.menus) {
    defaultCheckedMenu.value = currentUserInfo.menus;
  }
  let treeItemKey = ref([]);
  const treeItemId = ref(null); // 当前选中的菜单id, 1.用于添加子级, 点击添加顶级菜单, 需要设为null 2.用于删除

  let expandedKeys = ref([]);

  const treeData = ref([]);

  const loading = ref(true);
  const subLoading = ref(false);
  const isEditMenu = ref(false);
  const treeItemTitle = ref('');
  const pattern = ref('');
  const drawerTitle = ref('');

  const isAddSon = computed(() => {
    return !treeItemKey.value.length;
  });

  const addMenuOptions = ref([
    {
      label: '添加顶级菜单',
      key: 'home',
      disabled: false,
    },
    {
      label: '添加子菜单',
      key: 'son',
      disabled: isAddSon,
    },
  ]);

  const formParams = reactive({
    type: 1,
    name: '',
    // subtitle: '',
    path: '',
    permissions: '',
    hidden: 1,
    openType: 1,
  });

  function selectAddMenu(key: string) {
    drawerTitle.value = key === 'home' ? '添加顶栏菜单' : `添加子菜单：${treeItemTitle.value}`;
    openCreateDrawer();
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  // 前面的多选框选中
  function checkedTree(keys) {
    console.log('checkedTree', keys);
    updatePermissions(keys);
  }

  // 选中: 点击那一栏
  function selectedTree(keys) {
    console.log('selectedTree', keys);
    if (keys.length) {
      const treeItem = getTreeItem(unref(treeData), keys[0]);
      console.log('treeItem', treeItem);
      treeItemKey.value = keys;
      treeItemTitle.value = treeItem.label;
      treeItemId.value = treeItem.id;
      Object.assign(formParams, {
        id: treeItem.id,
        type: treeItem.type,
        name: treeItem.name,
        path: treeItem.path,
        permissions: treeItem.permissions,
        hidden: treeItem.hidden,
        openType: treeItem.openType,
        parentId: treeItem.parentId
      });
      isEditMenu.value = true;
    } else {
      isEditMenu.value = false;
      treeItemKey.value = [];
      treeItemTitle.value = '';
    }
  }

  function handleDel() {
    dialog.info({
      title: '提示',
      content: `您确定想删除[${formParams.name}]菜单吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        deleteById(treeItemId.value).then(res => {
          if(res.code == ResultEnum.SUCCESS) {
            message.success('删除成功');
            isEditMenu.value = false;
            getTreeMenuList();
          }
        });
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  function handleReset() {
    const treeItem = getTreeItem(unref(treeData), treeItemKey.value[0]);
    Object.assign(formParams, treeItem);
  }

  function formSubmit() {
    formRef.value.validate((errors: boolean) => {
      if (!errors) {
        saveMenu(formParams).then(() => {
          message.success("修改成功");
        });
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
    }
  }


  async function getTreeMenuList() {
    const { data: treeMenuList } = await getMenuList();
    console.log('treeMenuList', treeMenuList, currentUserInfo);
    const keys = treeMenuList.map((item) => item.key);
    Object.assign(formParams, keys);
    // treeData.value = treeMenuList;
    // 入乡随俗的处理
    treeData.value = [];
    treeMenuList.forEach((t) => {
      // 二级菜单处理
      if (t.children && t.children.length != 0) {
        let childrenMenuList = t.children;
        let tempList = [];
        childrenMenuList.forEach((c) => {
          // 菜单是否显示(如果是超级管理员, 不能取消”系统管理“、”菜单权限管理“、”角色权限管理“ 菜单, 如果是普通用户, 没有限制)
          let checkboxDisabled = false;

          if ((c.name == '菜单权限管理' || c.name == '角色权限管理' || c.name == '用户管理') && currentUserInfo.roleNameList.includes('平台管理员')) {
            checkboxDisabled = true;
          }
          tempList.push({...c, label: c.name, key: c.name, isLeaf: c.children.length <= 0, checkboxDisabled});
        });
        t.children = tempList;
      }
      // 菜单是否显示(如果是超级管理员, 不能取消”系统管理“、”菜单权限管理“、”角色权限管理“ 菜单, 如果是普通用户, 没有限制)
      let checkboxDisabled = false;
      if (t.name == '系统管理' && currentUserInfo.roleNameList.includes('平台管理员')) {
        checkboxDisabled = true;
      }
      treeData.value.push({...t, label: t.name, key: t.name,isLeaf: t.children.length <= 0, checkboxDisabled});
    });
    loading.value = false;
  }

  onMounted( () => {
    getTreeMenuList();
  });

  // 展开
  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>
